package com.hu.network.http.request;

import java.io.IOException;
import java.util.UUID;

import com.hu.network.http.HttpClient;
import com.hu.network.http.bean.InnerResponseResult;
import com.hu.network.http.bodyImpl.ResponseBodyImpl;
import com.hu.network.http.exception.NetException;

import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import timber.log.Timber;

/**
 * 说明：
 *
 * @author ： hucanhua
 * @date ： 2017/10/25
 */
public abstract class BaseHttpRequest<T> implements IHttpRequest<T>, Cloneable {

    protected final ProgressCallback requestCallback;
    protected final ProgressCallback responseCallback;
    private String tag;


    public BaseHttpRequest(final ProgressCallback requestCallback, final ProgressCallback responseCallback) {
        this.tag = UUID.randomUUID().toString();
        this.requestCallback = requestCallback;
        this.responseCallback = responseCallback;
    }

    protected abstract String getUrl();

    protected abstract T dealResponse(ResponseBody body) throws IOException;

    public abstract boolean useHttps();

    protected abstract Request getRequest() throws IllegalAccessException;

    public String getTag() {
        return tag;
    }


    @Override
    public void execute(InnerResponseResult<T> responseResult) throws IOException, NetException, IllegalAccessException {
        OkHttpClient http = useHttps() ? HttpClient.getInstance().getHttps() : HttpClient.getInstance().getHttp();

        Request request = getRequest();
        Call call = http.newCall(request);
        Response response = call.execute();
        responseResult.setCode(response.code());
        responseResult.setMessage(response.message());
        responseResult.setResponseResult(dealResponse(new ResponseBodyImpl(response.body(), new ResponseBodyImpl.ProgressListener() {
            @Override
            public void progress(long bytesRead, long contentLength, boolean done) {
                if (responseCallback != null) {
                    responseCallback.progress(bytesRead, contentLength, done);
                }
            }
        })));
        Timber.d("返回结果：%s", responseResult.getResponseResult());
        response.close();
    }

    public interface ProgressCallback {

        /**
         * 返回下载进度
         *
         * @param bytesRead     已经读取的字节数
         * @param contentLength 总长度
         * @param done          是否完成
         */
        void progress(long bytesRead, long contentLength, boolean done);
    }
}
